package com.yt.base.util;

import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.data.JRMapArrayDataSource;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRPdfExporterParameter;
import net.sf.jasperreports.engine.util.JRLoader;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class BarCodePrintUtil {
	public void print(ArrayList<HashMap<String, Object>> data, String template,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			String basePath = request.getSession().getServletContext()
					.getRealPath("/")
					+ "WEB-INF/report/";
			String reportFile = basePath + template;
			FileInputStream fis = new FileInputStream(reportFile);
			JRDataSource ds = new JRMapArrayDataSource(data.toArray());
			JasperPrint jasperPrint = JasperFillManager.fillReport(fis, null,
					ds);
			
			ServletOutputStream os = response.getOutputStream();
			JasperExportManager.exportReportToPdfStream(jasperPrint, os);
			os.flush();
			os.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	@SuppressWarnings("unchecked")
	public static void prints(List<ArrayList<HashMap<String,Object>>> reportList,String template ,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException, JRException {
		String path =request.getSession().getServletContext().getRealPath("/")+ "WEB-INF/report/";
		JasperReport jasperReport;
		JasperPrint jasperPrint;		
		JRDataSource dataSource;
		response.setContentType("application/pdf");
		try {
			File file = new File(path + "/" + template);
			jasperReport = (JasperReport) JRLoader.loadObject(file);
			List jaspList=new ArrayList();
			for (ArrayList<HashMap<String, Object>> arrayList : reportList) {
				dataSource  = new JRBeanCollectionDataSource(arrayList);
				jasperPrint = JasperFillManager.fillReport(jasperReport, null, dataSource);
				jaspList.add(jasperPrint);				
			}
			JRPdfExporter exporter = new JRPdfExporter();
			exporter.setParameter(JRPdfExporterParameter.JASPER_PRINT_LIST, jaspList);
			exporter.setParameter(JRPdfExporterParameter.CHARACTER_ENCODING,"UTF-8");
			exporter.setParameter(JRPdfExporterParameter.OUTPUT_STREAM,response.getOutputStream());
			exporter.exportReport();
		}catch(JRException e){
			e.printStackTrace();			
			throw new JRException(e);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
